package com.yinhe.music.yhmusic.music;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.request.transition.Transition;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.common.GlideHelper.BitmapTarget;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.common.view.RoundedImageView;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.base.BaseFragment;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.HandlerUtil;


public class QuickControlsFragment extends BaseFragment implements View.OnClickListener {

    private ProgressBar mProgress;
    private boolean isInitialized;
    private ImageView mPlayPause;
    private TextView mTitle;
    private TextView mArtist;
    private RoundedImageView mAlbumArt;
    private ImageView list;
    private int mode = 0;
    private boolean mNeedUpdate = false;

    private static Bitmap g_bitmap = null;
    private static String g_url = null;

    public static QuickControlsFragment newInstance() {
        return new QuickControlsFragment();
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.bottom_nav, container, false);
        RxBus.get().register(this);

        mPlayPause = rootView.findViewById(R.id.control);
        mProgress = rootView.findViewById(R.id.song_progress_normal);
        mTitle = rootView.findViewById(R.id.playbar_info);
        mArtist = rootView.findViewById(R.id.playbar_singer);
        mAlbumArt = rootView.findViewById(R.id.playbar_img);
        list = rootView.findViewById(R.id.play_list);

        mPlayPause.setOnClickListener(this);
        list.setOnClickListener(this);
        rootView.setOnClickListener(this);

        setProgress();
        initPlayingCard();

        return rootView;
    }

    private void setProgress() {
        mProgress.setMax(mService != null
                ? (int) mService.getDuration()
                : 100);
        mProgress.setProgress(0);
    }

    private void initPlayingCard() {
        if (mService != null && mService.getPlayingMusic() != null) {
            Music mPlayingMusic = mService.getPlayingMusic();
            updateNowPlayingCard(mPlayingMusic);
            mNeedUpdate = false;
        } else {
            mNeedUpdate = true;
        }
        isInitialized = true;
    }

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onServiceConnected(PlayService service) {
        super.onServiceConnected(service);
        if (mNeedUpdate) {
            mNeedUpdate = false;
            updateTrackInfo(service.getPlayingMusic());
        }
    }

    public void updateNowPlayingCard(final Music music) {
        if (music != null) {
            mTitle.setText(music.getSongName());
            mArtist.setText(music.getSingerName());

            if (TextUtils.isEmpty(music.getImage())) {
                mAlbumArt.setImageResource(R.drawable.default_cover);
            } else {
                if (g_bitmap != null && g_url != null && g_url.equals(music.getImage())) {
                    mAlbumArt.setImageBitmap(g_bitmap);
                } else {
                    mAlbumArt.setImageResource(R.drawable.default_cover);
                    GlideHelper.setCircleImageResource(getActivity(), music.getImage(), new BitmapTarget() {
                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            mAlbumArt.setImageBitmap(resource);
                            g_url = music.getImage();
                            g_bitmap = resource;
                        }
                    });
                }
            }
        } else {
            mTitle.setText("");
            mArtist.setText("");
            mAlbumArt.setImageResource(R.drawable.default_cover);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateTrackInfo();
    }

    public void updateState() {
        if (getActivity() != null && mService != null) {
            mProgress.setMax((int) mService.getDuration());
            mPlayPause.setImageResource(mService.isPlaying()
                    ? R.drawable.ic_stop_bottom
                    : R.drawable.ic_play_bottom);
        }
    }

    public void updateTrackInfo() {
        updateState();
        if (getActivity() != null && mService != null) {
            Music music = mService.getPlayingMusic();
            updateNowPlayingCard(music);
        }
    }


    public void updateTrackInfo(Music music) {
        updateNowPlayingCard(music);
        updateState();
        if (mService != null) {
            mProgress.setMax((int) mService.getDuration());
        }
    }

    public void updateTime() {
        if (mService != null) {
            mProgress.setMax((int) mService.getDuration());
        }
    }

    public boolean isInitialized() {
        return isInitialized;
    }

    /**
     * 更新播放进度
     */
    public void onPublish(int progress) {
        mProgress.setProgress(progress);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.control: {
                if (mService != null
                        && mService.getPlayList().isEmpty()
                        && mService.getPlayingMusic() == null) {
                    Toast.makeText(AppCache.getContext(), getResources().getString(R.string.queue_is_empty),
                            Toast.LENGTH_SHORT).show();
                } else {
                    HandlerUtil.getInstance(AppCache.getContext()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mService != null) mService.playPause();
                        }
                    }, 60);
                }
                break;
            }

            case R.id.play_list: {
                if (mService != null) {
                    showPlayingList();
                }
                break;
            }
            case R.id.nav_play: {
                if (mService != null
                        && mService.getPlayList() != null
                        && mService.getPlayingMusic() != null) {
                    Intent intent = new Intent(AppCache.getContext(), PlayingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("mode", mode);
                    startActivity(intent);
                }
                break;
            }
            default:
                break;

        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.CLEAR_PLAYLIST)
    )
    public void onRxbusPlayingMode(RxbusNullObject rxbusNullObject) {
        updateTrackInfo();
    }
}